//
//
//
//
//  Created by wulanzhou on 16-3-7.
//  Copyright (c) 2016年 . All rights reserved.
//

#import "WBServiceManager.h"
@interface WBServiceManager (){
    NSMutableDictionary *_requestDict;
}
@end

@implementation WBServiceManager

+ (WBServiceManager *)shareInstance
{
    static dispatch_once_t  onceToken;
    static WBServiceManager * sSharedInstance;
    
    dispatch_once(&onceToken, ^{
        sSharedInstance = [[WBServiceManager alloc] init];
    });
    return sSharedInstance;
}

- (id)init
{
    self = [super init];
    if (self)
    {
        _requestDict = [NSMutableDictionary dictionaryWithCapacity:2];
    }
    return self;
}

/**
 *  request(无参请求,默认请求方式为post)
 *
 *  @param methodName       请求方法名
 *  @param completed        请求完成的block
 *
 */
- (void)requestServiceWithMethodName:(NSString*)methodName completed:(void(^)(WBResponse *response))finished{

    WBRequestArgs *args=[[WBRequestArgs alloc] init];
    args.methodName=methodName;
    [self requestServiceWithArgs:args completed:finished];
}

/**
 *  request(有参请求,默认请求方式为post)
 *
 *  @param methodName       请求方法名
 *  @param parameters       请求参数
 *  @param completed        请求完成的block
 *
 */
- (void)requestServiceWithMethodName:(NSString*)methodName parameters:(NSDictionary *)params completed:(void(^)(WBResponse *response))finished{
    WBRequestArgs *args=[[WBRequestArgs alloc] init];
    args.methodName=methodName;
    if (params&&[params isKindOfClass:[NSDictionary class]]&&[params count]>0) {
        [args addParamWithDictionary:params];
    }
    [self requestServiceWithArgs:args completed:finished];
}

/**
 *  request请求
 *
 *  @param args             请求参数对象
 *  @param completed        请求完成的block
 *
 */
- (void)requestServiceWithArgs:(WBRequestArgs*)args completed:(void(^)(WBResponse *response))finished{
    
    @synchronized(_requestDict)
    {
        WBRequestObj *requestObj = [[WBRequestObj alloc] init];
        [_requestDict setObject:requestObj forKey:args.requestKey];
        requestObj.RequestFinishedServiceManager=finished;
        [requestObj requestService:args delegate:self];
    }
}

/**
 *  request请求停止
 *
 *  @param requestName  停止请求名称
 *
 */
- (void)stopRequestWithName:(NSString*)requestName{
    @synchronized(_requestDict)
    {
        WBRequestObj *tempRequest = [_requestDict objectForKey:requestName];
        if(tempRequest)
        {
            [tempRequest stopRequest];
            [_requestDict removeObjectForKey:requestName];
        }
    }
}
#pragma mark -CZRequestObjDelegate Methods
- (void)CZRequestFinished:(WBRequestObj*)requestObj resultResponse:(WBResponse *)response{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    requestObj.delegate=nil;
    [_requestDict removeObjectForKey:requestObj.requestArgs.requestKey];
    if (requestObj.RequestFinishedServiceManager) {
        requestObj.RequestFinishedServiceManager(response);
    }
}

@end
